package com.tencent.qf.goods.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencent.qf.goods.dao.DmAppSpuSalesInfoDao;
import com.tencent.qf.goods.dto.db.RecommendSpuDto;
import com.tencent.qf.goods.dto.request.RecommendSpuRequest;
import com.tencent.qf.goods.service.DmAppSpuSalesInfoService;
import com.tencent.qf.mybatis.pojo.PageRequest;
import com.tencent.qf.mybatis.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class DmAppSpuSalesInfoServiceImpl implements DmAppSpuSalesInfoService {
    @Autowired
    private DmAppSpuSalesInfoDao dmAppSpuSalesInfoDao;

    /**
     * 数据快照获取推荐商品
     *
     * @param request
     * @return
     */
    @Override
    public PageResult<RecommendSpuDto> recommendSpu(PageRequest<RecommendSpuRequest> request) {
        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        List<RecommendSpuDto> list = dmAppSpuSalesInfoDao.recommendSpu(request.getData());
        PageInfo<RecommendSpuDto> pageInfo = new PageInfo(list);
        this.doLimit(pageInfo, request);
        return PageResult.build(pageInfo);
    }

    /**
     * 限制只返回spuLimit个数据，多的需要截断
     *
     * @param pageInfo
     * @param request
     */
    private void doLimit(PageInfo<RecommendSpuDto> pageInfo, PageRequest<RecommendSpuRequest> request) {
        if (CollectionUtils.isEmpty(pageInfo.getList())) {
            return;
        }
        if (request.getData() == null) {
            return;
        }
        Integer spuLimit = request.getData().getSpuLimit();
        if (spuLimit == null || spuLimit <= 0) {
            return;
        }
        if (pageInfo.getTotal() <= spuLimit.intValue()) {
            return;
        }
        pageInfo.setTotal(spuLimit);
        Integer currStartIndex = (request.getPageNo() - 1) * request.getPageSize();
        Integer currEndIndex = request.getPageNo() * request.getPageSize();
        if (currStartIndex < spuLimit && currEndIndex > spuLimit) {
            pageInfo.setList(pageInfo.getList().subList(0, request.getPageSize() - (currEndIndex - spuLimit)));
        }
    }
}
